﻿/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.html
*******************************************************************************/


(function (K) {

    function KH5Upload(options) {
        this.init(options);
    }
    var formDataList = new Array();
    var formFileList = new Array();
    var fileId = 0;

    K.extend(KH5Upload, {
        init: function (options) {
            var self = this;
            options.afterError = options.afterError || function (str) {
                alert(str);
            };
            self.options = options;
            self.progressbars = {};
            // template
            self.div = K(options.container).html([
                '<div class="ke-swfupload">',
                '<div class="ke-swfupload-top">',
                '<div class="ke-inline-block ke-button-common" style="width: 72px;height: 23px;position: relative;text-align: center;">',
                //'<input type="button" value="Browse" />',
                '<span class="ke-button-common ke-button" style="position: absolute;top: 0px;bottom: 0;left: 0;right: 0;margin: auto;">添加图片</span>',
                '<input type="file" name="uploadfile" id="uploadfile" accept="image/png,image/jpeg,image/gif" multiple style="opacity: 0;width: 100%;height: 100%;cursor: pointer;">',
                '</div>',
                '<div class="ke-inline-block ke-swfupload-desc">' + options.uploadDesc + '</div>',
                '<span class="ke-button-common ke-button-outer ke-swfupload-startupload">',
                '<input type="button" class="ke-button-common ke-button" value="' + options.startButtonValue + '" />',
                '</span>',
                '</div>',
                '<div class="ke-swfupload-body"></div>',
                '</div>'
            ].join(''));
            self.bodyDiv = K('.ke-swfupload-body', self.div);

            function showError(itemDiv, msg) {
                K('.ke-status > div', itemDiv).hide();
                K('.ke-message', itemDiv).addClass('ke-error').show().html(K.escape(msg));
            }

            /*H5上传新增内容开始*/
            var input = document.getElementById("uploadfile");

            input.onchange = function () {
                readFile(this);
            }

            var readFile = function (obj) {
                var fileList = obj.files;
                var isAdd = true;
                for (var i = 0; i < fileList.length; i++) {
                    if (fileList[i].type == 'image/png' || fileList[i].type == 'image/jpeg' || fileList[i].type == 'image/gif') {
                        if (fileList[i].size <= 1024 * 1024 * parseInt(options.fileSizeLimit.replace('M', ''))) {
                            isAdd = true;
                            if (formFileList.length > 0) {
                                for (var j = 0; j < formFileList.length; j++) {
                                    if (formFileList[j].name == fileList[i].name) {
                                        isAdd = false;
                                        continue;
                                    }
                                }
                            }
                            if (isAdd) {
                                fileList[i].id = "file_id_" + fileId + "";
                                fileList[i].url = self.options.fileIconUrl;
                                fileList[i].filestatus = '-1';
                                fileId++;
                                self.appendFile(fileList[i]);

                                var formData = new FormData();
                                formData.append("imgFile", fileList[i], fileList[i].name);
                                formDataList.push(formData);
                                formFileList.push(fileList[i]);
                            }
                        } else {
                            //console.log(fileList[i].name + ' - 文件上传超出最大允许上限:' + fileList[i].size + '');
                        }
                    } else {
                        //console.log('不支持的文件类型:' + fileList[i].type + '');
                    }
                }

            }
            /*H5上传新增内容结束*/

            K('.ke-swfupload-startupload input', self.div).click(function () {
                //self.swfu.startUpload();
                var uplaodFile = false;
                for (var i = 0; i < formDataList.length; i++) {
                    if (formFileList[i].filestatus == '-1') {
                        uplaodFile = true;
                        uploadImage(formFileList[i], formDataList[i]);
                    }
                }
                if (!uplaodFile) {
                    alert('文件都已上传完毕');
                }

            });

            function uploadImage(formFileItem, formDataItem) {
                var time = new Date().getTime();
                var percentage = null;
                var velocity = null;
                var loaded = 0;
                var itemDiv = K('div[data-id="' + formFileItem.id + '"]', self.bodyDiv).eq(0);
                var file = formFileItem;
                $.ajax({
                    "url": options.uploadUrl,
                    "type": "POST",
                    "data": formDataItem,
                    "contentType": false,
                    "processData": false,
                    "success": function (data) {
                        data = JSON.parse(data);
                        if (data.error !== 0) {
                            showError(itemDiv, K.DEBUG ? data.message : self.options.errorMessage);
                            return;
                        } else {
                            file.url = data.url;
                            file.filestatus = '-4';
                            data.title = formFileItem.name.substring(0, formFileItem.name.indexOf("."));
                            K('.ke-img', itemDiv).attr('src', file.url).attr('data-status', file.filestatus).data('data', data);
                            K('.ke-status > div', itemDiv).hide();
                        }

                    },
                    "xhr": function xhr() {
                        var xhr = $.ajaxSettings.xhr();
                        K('.ke-message', itemDiv).hide();
                        K('.ke-progressbar', itemDiv).show();
                        if (xhr.upload) {
                            xhr.upload.addEventListener('progress', function (e) {
                                var nowDate = new Date().getTime();
                                var percent = Math.round(e.loaded * 100 / e.total);
                                var progressbar = self.progressbars[file.id];
                                progressbar.bar.css('width', Math.round(percent * 80 / 100) + 'px');
                                progressbar.percent.html(percent + '%');
                            }, false);
                        }
                        return xhr;
                    },
                    "error": function (data) {

                    }
                });
            }
        },
        getUrlList: function () {
            var list = [];
            K('.ke-img', self.bodyDiv).each(function () {
                var img = K(this);
                var status = img.attr('data-status');
                if (status == '-4') {
                    list.push(img.data('data'));
                }
            });
            return list;
        },
        removeFile: function (fileId) {
            var self = this;
            //self.swfu.cancelUpload(fileId);
            var itemDiv = K('div[data-id="' + fileId + '"]', self.bodyDiv);
            K('.ke-photo', itemDiv).unbind();
            K('.ke-delete', itemDiv).unbind();
            itemDiv.remove();
            formDataList = new Array();
            formFileList = new Array();
        },
        removeFiles: function () {
            var self = this;
            K('.ke-item', self.bodyDiv).each(function () {
                self.removeFile(K(this).attr('data-id'));
            });
        },
        appendFile: function (file) {
            var self = this;
            var itemDiv = K('<div class="ke-inline-block ke-item" data-id="' + file.id + '"></div>');
            self.bodyDiv.append(itemDiv);
            var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
                .mouseover(function (e) {
                    K(this).addClass('ke-on');
                })
                .mouseout(function (e) {
                    K(this).removeClass('ke-on');
                });
            itemDiv.append(photoDiv);

            var img = K('<img src="' + file.url + '" class="ke-img" data-status="' + file.filestatus + '" width="80" height="80" alt="' + file.name + '" />');
            photoDiv.append(img);
            K('<span class="ke-delete"></span>').appendTo(photoDiv).click(function () {
                self.removeFile(file.id);
            });
            var statusDiv = K('<div class="ke-status"></div>').appendTo(photoDiv);
            // progressbar
            K(['<div class="ke-progressbar">',
                '<div class="ke-progressbar-bar"><div class="ke-progressbar-bar-inner"></div></div>',
                '<div class="ke-progressbar-percent">0%</div></div>'].join('')).hide().appendTo(statusDiv);
            // message
            K('<div class="ke-message">' + self.options.pendingMessage + '</div>').appendTo(statusDiv);

            itemDiv.append('<div class="ke-name">' + file.name + '</div>');

            self.progressbars[file.id] = {
                bar: K('.ke-progressbar-bar-inner', photoDiv),
                percent: K('.ke-progressbar-percent', photoDiv)
            };
        },
        remove: function () {
            this.removeFiles();
            //this.swfu.destroy();
            this.div.html('');
            formDataList = new Array();
            formFileList = new Array();
        }
    });

    K.h5upload = function (element, options) {
        return new KH5Upload(element, options);
    };

})(KindEditor);

KindEditor.plugin('multiimage', function (K) {
    var self = this, name = 'multiimage',
		formatUploadUrl = K.undef(self.formatUploadUrl, true),
		uploadJson = K.undef(self.uploadJson, self.basePath + 'asp.net/upload_json.ashx'),
		imgPath = self.pluginsPath + 'multiimage/images/',
		imageSizeLimit = K.undef(self.imageSizeLimit, '3MB'),
		imageFileTypes = K.undef(self.imageFileTypes, '*.jpg;*.gif;*.png'),
		imageUploadLimit = K.undef(self.imageUploadLimit, 100),
		filePostName = K.undef(self.filePostName, 'imgFile'),
		lang = self.lang(name + '.');

    self.plugin.multiImageDialog = function (options) {
        var clickFn = options.clickFn,
			uploadDesc = K.tmpl(lang.uploadDesc, { uploadLimit: imageUploadLimit, sizeLimit: imageSizeLimit });
        var html = [
			'<div style="padding:20px;">',
			'<div class="swfupload">',
			'</div>',
			'</div>'
        ].join('');
        var dialog = self.createDialog({
            name: name,
            width: 650,
            height: 310,
            title: self.lang(name),
            body: html,
            previewBtn: {
                name: lang.insertAll,
                click: function (e) {
                    clickFn.call(self, h5upload.getUrlList());
                }
            },
            yesBtn: {
                name: lang.clearAll,
                click: function (e) {
                    h5upload.removeFiles();
                }
            },
            beforeRemove: function () {
                h5upload.remove();
            }
        }),
		div = dialog.div;

        var h5upload = K.h5upload({
            container: K('.swfupload', div),
            buttonImageUrl: imgPath + (self.langType == 'zh_CN' ? 'select-files-zh_CN.png' : 'select-files-en.png'),
            buttonWidth: self.langType == 'zh_CN' ? 72 : 88,
            buttonHeight: 23,
            fileIconUrl: imgPath + 'image.png',
            uploadDesc: uploadDesc,
            startButtonValue: lang.startUpload,
            uploadUrl: K.addParam(uploadJson, '&dir=image&multi=images'),
            filePostName: filePostName,
            fileTypes: '*.jpg;*.jpeg;*.gif;*.png;*.bmp',
            fileTypesDesc: 'Image Files',
            fileUploadLimit: imageUploadLimit,
            fileSizeLimit: imageSizeLimit,
            postParams: K.undef(self.extraFileUploadParams, {}),
            queueLimitExceeded: lang.queueLimitExceeded,
            fileExceedsSizeLimit: lang.fileExceedsSizeLimit,
            zeroByteFile: lang.zeroByteFile,
            invalidFiletype: lang.invalidFiletype,
            unknownError: lang.unknownError,
            pendingMessage: lang.pending,
            errorMessage: lang.uploadError,
            afterError: function (html) {
                self.errorDialog(html);
            }
        });

        return dialog;
    };
    self.clickToolbar(name, function () {
        self.plugin.multiImageDialog({
            clickFn: function (urlList) {
                if (urlList.length === 0) {
                    return;
                }
                K.each(urlList, function (i, data) {
                    if (self.afterUpload) {
                        self.afterUpload.call(self, data.url, data, 'multiimage');
                    }
                    self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align);
                });
                // Bugfix: [Firefox] 上传图片后，总是出现正在加载的样式，需要延迟执行hideDialog
                setTimeout(function () {
                    self.hideDialog().focus();
                }, 0);
            }
        });
    });
});
